<template>
  <div class="upload-container">
    <a-upload
      :headers="headers"
      v-model:file-list="fileList"
      name="file"
      list-type="picture-card"
      class="avatar-uploader"
      :accept="'.jpg, .jpeg, .icon, .png, .gif'"
      :show-upload-list="false"
      :action="action"
      :before-upload="beforeUpload"
      @change="handleChange"
      @remove="handleRemove"
    >
      <img
        v-if="imageUrl"
        :src="imageUrl"
        alt="avatar"
        style="overflow: hidden !important; object-fit: contain !important"
      />
      <div v-else>
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
        <div class="ant-upload-text">上传</div>
      </div>
    </a-upload>
    <span class="upload-tip">支持jpg、jpeg、png、gif格式，大小不超过10M</span>
    <a-button v-if="imageUrl" @click="openImageInNewTab(imageUrl)" type="link">预览图片</a-button>
  </div>
</template>

<script setup lang="ts">
import { message } from "ant-design-vue";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons-vue";
const headers = computed(() => {
  const user = JSON.parse(localStorage.getItem("__persisted__user") || "{}");
  return {
    Authorization: `Bearer ${user.token}`,
  };
});
const props = defineProps({
  action: {
    type: String,
    default: "/api/admin/upload",
  },
  modelValue: {
    type: String,
    default: "",
  },
});
const imageUrl = ref<string>("");
watch(
  () => props.modelValue,
  (newVal) => {
    imageUrl.value = newVal;
  },
  {
    immediate: true,
  }
);

function getBase64(img: Blob, callback: (base64Url: string) => void) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result as string));
  reader.readAsDataURL(img);
}

const fileList = ref([]);
const loading = ref<boolean>(false);
const emit = defineEmits(["update:modelValue"]);
const baseUrl = import.meta.env.VITE_BASE_OSS_URL;
const PORT = import.meta.env.VITE_API_PORT;

const handleChange = (info: UploadChangeParam) => {
  if (info.file.status === "uploading") {
    loading.value = true;
    return;
  }
  if (info.file.status === "done") {
    // Get this url from response in real world.
    getBase64(info.file.originFileObj, (base64Url: string) => {
      imageUrl.value = base64Url;
      loading.value = false;
    });
    emit(
      "update:modelValue",
      info.file.response ? baseUrl + "/" + info.file.response.data : ""
    );
  }
  if (info.file.status === "error") {
    loading.value = false;
    message.error(info.file.response.message);
  }
};
const handleRemove = (file: UploadFile) => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
  emit(
    "update:modelValue",
    newFileList.map((item) => {
      if (isReactive(item)) {
        return item.url;
      } else {
        return item.response ? baseUrl + "/upload/" + item.response.data : "";
      }
    })
  );
};
const beforeUpload = (file: UploadProps["fileList"][number]) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("You can only upload JPG file!");
  }
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error("Image must smaller than 10MB!");
  }
  return isJpgOrPng && isLt10M;
};

const openImageInNewTab = (url: string) => {
  window.open(url, '_blank');
};
</script>

<style scoped lang="less">
.upload-container {
  width: 400px !important;
  max-height: 400px !important;
  border: 1px solid #e6e6e6;
  padding: 10px;

  .ant-upload {
    max-width: 400px !important;
    max-height: 400px !important;
  }

  .ant-upload img {
    max-width: 400px !important;
    max-height: 400px !important;
  }

  .ant-upload-select {
    max-width: 400px !important;
    max-height: 400px !important;
  }

  .ant-upload-select-picture-card {
    max-width: 400px !important;
    max-height: 400px !important;
  }

  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    color: #666;
  }
}

</style>
